package com.example.administrator.choosephototest;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    public static final int TAKE_PHOTO=1;//拍照
    public static final int CROP_PHOTO=2;//图片裁剪
    public static final int CHOOSE_PHOTO=3;//相册选择
    private Button take_photo;
    private ImageView photo;
    private Button choose;
    private static Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        take_photo= (Button) findViewById(R.id.bt1);
        photo= (ImageView) findViewById(R.id.pic);
        choose= (Button) findViewById(R.id.choose);

        take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File outputImage=new File(Environment.getExternalStorageDirectory(),"photo.jpg");//获取根目录，用于存储拍照后的照片
                try{
                    if(outputImage.exists()){
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                }catch (Exception e){
                    e.printStackTrace();
                }
                imageUri=Uri.fromFile(outputImage);
                Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);//图像输出存储
                startActivityForResult(intent,TAKE_PHOTO);//启动相机程序
                
            }
        });
        choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent("android.intent.action.GET_CONTENT");
                intent.setType("image/*");
                startActivityForResult(intent,CHOOSE_PHOTO);//启动相册
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case TAKE_PHOTO:
                if(resultCode==RESULT_OK){
                    setCropPhoto();
                }
                break;
            case CROP_PHOTO:
                if(resultCode==RESULT_OK){
                    try{
                        Bitmap bp= BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        photo.setImageBitmap(bp);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if(resultCode==RESULT_OK){
                    //判断手机系统的版本号，4.4版本开始将从相册中选取图片返回的Uri进行了改动
                    if(Build.VERSION.SDK_INT>=19)
                        handleImageOnKitKat(data);
                    else
                        handleImageBeforeKitKat(data);
                }
                break;
        }
    }
    
    //手机系统高于4.4（包括4.4）   选取相册中的图片不再返回图片真实的Uri，而是一个封装过的Uri，需要进行解析
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data){
        String imagePath=null;
        Uri uri=data.getData();
        //如果是document类型的Uri，则通过document id处理
        if(DocumentsContract.isDocumentUri(this,uri)){
            String docid=DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id=docid.split(":")[1];//解析出数字格式的id
                String selection=MediaStore.Images.Media._ID+"="+id;
                imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docid));
                imagePath=getImagePath(contentUri,null);
            }
        }else if("content".equalsIgnoreCase(uri.getScheme())){
            //如果不是document类型的Uri，则使用普通方式处理
            imagePath=getImagePath(uri,null);
        }
        displayImage(imagePath);
    }

    //手机系统低于4.4执行方法  
    private void handleImageBeforeKitKat(Intent data){
        Uri uri=data.getData();
        String iamgePath=getImagePath(uri,null);
        displayImage(iamgePath);
    }
    
    private String getImagePath(Uri uri,String selection){
        String path=null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor=getContentResolver().query(uri,null,selection,null,null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    
    private void displayImage(String imagePath){
        if(imagePath!=null){
            imageUri=Uri.parse("file://"+imagePath);//图片路径String类型转换成Uri
            setCropPhoto();
            
            //不通过裁剪直接显示图片
//            Bitmap bitmap=BitmapFactory.decodeFile(imagePath);
//            photo.setImageBitmap(bitmap);
        }else {
            Toast.makeText(this,"failed to load...",Toast.LENGTH_LONG).show();
        }
    }
    
    //图片裁剪
    private void setCropPhoto(){
        Intent intent=new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imageUri,"image/*");
        intent.putExtra("scale",true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        startActivityForResult(intent,CROP_PHOTO);//启动图片裁剪程序
    }

}
